package com.sky.controller.user;

import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user/addressBook")
@Api(tags = "地址簿")
public class AddressController {
    @Autowired
    private AddressService service;

    /**
     * 根据id查询地址簿
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据地址簿查询id")
    public Result<AddressBook> AddressBookById(@PathVariable Long id) {
        List<AddressBook> listByid = service.AddressBookById(id);
        AddressBook addressBook = listByid.get(0);
        return Result.success(addressBook);
    }

    /**查询当前登录用户的所有地址信息
     *
     * @return
     */
    @ApiOperation("查询当前登录用户的所有地址信息")
    @GetMapping("/list")
    public Result<List<AddressBook>> list() {
        log.info("查询当前登录用户的所有地址信息");
        List<AddressBook> addressBooklist = service.showAddressBook();
        return Result.success(addressBooklist);
    }

    /**
     * 查询默认地址
     * @return
     */
    @ApiOperation("设置默认地址")
    @GetMapping("/default")
    public Result<List<AddressBook>> defaultAddressBook() {
        log.info("查询默认地址");
        List<AddressBook> isDefaultAddressList = service.showDefaultAddressBook();
        return Result.success(isDefaultAddressList);
    }

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    @ApiOperation("新增地址")
    @PostMapping
    public Result addAddressBook(@RequestBody AddressBook addressBook) {
        log.info("新增地址");
        service.addAddressBook(addressBook);
        return Result.success();
    }

    /**
     * 修改前端传过来的数据，若数据为空，则会报未知错误
     * @param addressBook
     * @return
     */
    @PutMapping
    @ApiOperation("根据id修改地址簿")
    public Result updateAddressBook(@RequestBody AddressBook addressBook) {
        log.info("根据id修改地址簿:{}", addressBook);
        service.updateAddressBook(addressBook);
        return Result.success();
    }

    @PutMapping("/default")
    @ApiOperation("修改默认地址")
    public Result updateDefaultAddressBook(@RequestBody AddressBook addressBook) {
        log.info("修改默认地址:{}", addressBook);
        service.updateDefaultAddressBook(addressBook);
        return Result.success();
    }

    @DeleteMapping()
    @ApiOperation("根据id删除一条地址信息")
    public Result deleteAddressBook(  Long id) {
        log.info("根据id删除一条地址信息:{}",id);
        service.deleteAddressBook(id);
        return Result.success();
    }

}
